package cn.jisol.network;

import cn.jisol.ngame.client.NClient;
import cn.jisol.ngame.network.JNetwork;
import org.springframework.stereotype.Controller;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(
    value = "/websocket"
)
@Controller
public class WebSocket {

    public static final Map<String, NClient> CLIENTS = new ConcurrentHashMap<>();


    @OnOpen
    public void onOpen(Session session){
        CLIENTS.put(session.getId(),new NClient(session));
        System.out.printf("[WebSocket] %s 连接成功.\n",session.getId());
    }

    @OnMessage
    public void onMessage(Session session, InputStream inputStream){
        JNetwork.onMessage(inputStream,CLIENTS.get(session.getId()),CLIENTS);
    }

    @OnClose
    public void onClose(Session session){
        CLIENTS.remove(session.getId());
    }

}
